from Bases import BaseObject
from baseview import BaseView
from ..devicetree import DeviceTree
from ..bases import widgets
from .. import editors

class PatchView(BaseView):
    topwidget_name = 'Patch Editor'
    topwidget_cls = widgets.HPane
    def __init__(self, **kwargs):
        self.topwidget = widgets.VBox()
        super(PatchView, self).__init__(**kwargs)
        self.DeviceSystem = self.MainController.DeviceSystem
        self.patch_editor = None
        
        frame = self.make_child_widget(widgets.Frame, 'frame1', label='Definitions')
        col_names = ['id', 'name']
        obj_names = ['DefinedDevice']
        self.device_list = DeviceTree(col_names=col_names, obj_names=obj_names, child_name_attr='none', 
                                      show_dicts=False, base_dict=self.DeviceSystem.DefinedDevices, used_columns=[1])
        self.device_list.widget.connect('selection_changed', self.on_device_list_selection_changed)
        frame.pack_start(self.device_list.widget.topwidget, expand=True)
        
        self.topcontainer.pack_start(frame)
        
        self.topwidget.show_all()
        
    def set_current_device(self, obj):
        if self.patch_editor is not None:
            self.remove_editor(self.patch_editor)
        self.add_editor(editors.PatchEditor, 'patch_editor', definition=obj)
        self.topcontainer.pack_start(self.patch_editor.topwidget)
        
    def on_device_list_selection_changed(self, **kwargs):
        obj = kwargs.get('obj')
        state = kwargs.get('state')
        if state and hasattr(obj, 'id'):
            self.set_current_device(obj)
